// pages/gallery/upload/index.js
Page({
  data: {
    pic_list: [
    ]
  },
  onLoad: function (options) {
    console.log(123123123)
  },
  removeImage (e) {
    let item = e.currentTarget.dataset.url
    let index = this.data.pic_list.indexOf(item)
    this.data.pic_list.splice(index, 1)
    this.setData({
      pic_list: this.data.pic_list
    })
  },
  previewImage (e) {
    let item = e.currentTarget.dataset.url
    tt.previewImage({
      urls: this.data.pic_list,
      current: item
    })
  },
  uploadPic () {
    tt.chooseImage({
      count: 100 - this.data.pic_list.length,
      success: (res) => {
        this.data.pic_list = this.data.pic_list.concat(res.tempFilePaths);
        this.setData({
          pic_list: this.data.pic_list
        })
      },
      fail (res) {
        console.log(`chooseImage调用失败`);
      }
    });
  },
  addOrder () {
    tt.showLoading({title: '上传中，请稍后...'});
    let pidList = []
    let uploadList = this.data.pic_list.map((item, index) => new Promise((resolve, reject) => {
      tt.uploadFile({
        url: 'https://douyinmini.163ar.cn/admin/system/upload', // 目标地址
        filePath: item, // 本地文件路径
        name: 'file', // HTTP请求的文件名
        success: (res) => {
          let data = JSON.parse(res.data)
          pidList[index] = 'https://douyinmini.163ar.cn' + data.url
          resolve(res)
        },
        fail: (err) => {
          reject('上传失败')
        }
      });
    }))
    Promise.all(uploadList).then(res => {
      tt.hideLoading()
      tt.setStorageSync('gallery__select', pidList);
      tt.redirectTo({
        url: '/pages/gallery/order/add/index' 
      })
    }).catch(err => {
      tt.hideLoading()
    })
  }
})